def load_dictionary(file_path):
    try:
        with open(file_path, 'r', encoding='utf-8') as file:
            dictionary = {}
            for line in file:
                word, translation = line.strip().split(' ')
                dictionary[word] = translation
            return dictionary
    except FileNotFoundError:
        print("词典文件不存在，将创建一个新的词典。")
        return {}


def save_dictionary(dictionary, file_path):
    with open(file_path, 'w', encoding='utf-8') as file:
        for word, translation in dictionary.items():
            file.write(f"{word} {translation}\n")


def add_word(dictionary):
    word = input("请输入要添加的英文单词：")
    if word in dictionary:
        print("该单词已添加到字典库。")
    else:
        translation = input("请输入该单词的中文释义：")
        dictionary[word] = translation
        print("单词添加成功。")


def search_word(dictionary):
    word = input("请输入要查询的英文单词：")
    translation = dictionary.get(word)
    if translation:
        print(f"{word}: {translation}")
    else:
        print("字典库中未找到这个单词。")


def main():
    file_path = 'dictionary.txt'
    dictionary = load_dictionary(file_path)

    while True:
        print("\n欢迎使用英文学习词典：")
        print("1. 添加单词")
        print("2. 查询单词")
        print("3. 退出")

        choice = input("请选择操作（输入对应数字）：")

        if choice == '1':
            add_word(dictionary)
        elif choice == '2':
            search_word(dictionary)
        elif choice == '3':
            save_dictionary(dictionary, file_path)
            print("词典已保存，感谢使用。")
            break
        else:
            print("输入有误，请重新输入。")


if __name__ == "__main__":
    main()
